import React, { useState } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Tag,
  Avatar,
  Modal,
  Form,
  Input,
  Select,
  message,
  Typography,
  Image,
  Row,
  Col,
  Divider,
} from 'antd';
import {
  CheckOutlined,
  CloseOutlined,
  EyeOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { formatDate } from '@/utils';

const { Title, Text } = Typography;
const { TextArea } = Input;

interface ReviewItem {
  id: string;
  user: {
    id: string;
    nickname: string;
    avatar?: string;
    age: number;
    gender: 'male' | 'female';
  };
  submitTime: string;
  type: 'profile' | 'photo' | 'certification';
  status: 'pending' | 'approved' | 'rejected';
  content?: string;
  photos?: string[];
}

const UserReview: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [reviewModalVisible, setReviewModalVisible] = useState(false);
  const [selectedItem, setSelectedItem] = useState<ReviewItem | null>(null);
  const [form] = Form.useForm();

  // 模拟待审核数据
  const mockReviewData: ReviewItem[] = [
    {
      id: '1',
      user: {
        id: '1',
        nickname: '李小花',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=female1',
        age: 26,
        gender: 'female',
      },
      submitTime: '2024-01-20T14:25:00Z',
      type: 'profile',
      status: 'pending',
      content: '资深设计师，热爱生活，希望找到志同道合的伴侣。',
    },
    {
      id: '2',
      user: {
        id: '2',
        nickname: '王明',
        avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=male1',
        age: 28,
        gender: 'male',
      },
      submitTime: '2024-01-20T13:15:00Z',
      type: 'photo',
      status: 'pending',
      photos: [
        'https://picsum.photos/300/400?random=5',
        'https://picsum.photos/300/400?random=6',
      ],
    },
  ];

  const getTypeTag = (type: string) => {
    const typeMap = {
      profile: { color: 'blue', text: '资料审核' },
      photo: { color: 'green', text: '照片审核' },
      certification: { color: 'orange', text: '认证审核' },
    };
    const config = typeMap[type as keyof typeof typeMap];
    return <Tag color={config?.color}>{config?.text}</Tag>;
  };

  const columns = [
    {
      title: '用户信息',
      key: 'user',
      render: (_, record: ReviewItem) => (
        <Space>
          <Avatar
            src={record.user.avatar}
            icon={<UserOutlined />}
            size={40}
          />
          <div>
            <div>{record.user.nickname}</div>
            <Text type="secondary" style={{ fontSize: '12px' }}>
              {record.user.age}岁 • {record.user.gender === 'male' ? '男' : '女'}
            </Text>
          </div>
        </Space>
      ),
    },
    {
      title: '审核类型',
      key: 'type',
      render: (_, record: ReviewItem) => getTypeTag(record.type),
    },
    {
      title: '提交时间',
      key: 'submitTime',
      render: (_, record: ReviewItem) => formatDate(record.submitTime),
    },
    {
      title: '状态',
      key: 'status',
      render: (_, record: ReviewItem) => {
        const statusMap = {
          pending: { color: 'orange', text: '待审核' },
          approved: { color: 'green', text: '已通过' },
          rejected: { color: 'red', text: '已驳回' },
        };
        const config = statusMap[record.status];
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record: ReviewItem) => (
        <Space>
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => handleReview(record)}
          >
            审核
          </Button>
          <Button
            type="text"
            icon={<CheckOutlined />}
            style={{ color: '#52c41a' }}
            onClick={() => handleQuickApprove(record)}
          >
            通过
          </Button>
          <Button
            type="text"
            icon={<CloseOutlined />}
            danger
            onClick={() => handleQuickReject(record)}
          >
            驳回
          </Button>
        </Space>
      ),
    },
  ];

  const handleReview = (item: ReviewItem) => {
    setSelectedItem(item);
    setReviewModalVisible(true);
  };

  const handleQuickApprove = (item: ReviewItem) => {
    Modal.confirm({
      title: '确定通过审核？',
      content: `确定通过 ${item.user.nickname} 的${getTypeTag(item.type).props.children}？`,
      onOk: () => {
        message.success('审核通过');
      },
    });
  };

  const handleQuickReject = (item: ReviewItem) => {
    Modal.confirm({
      title: '确定驳回审核？',
      content: `确定驳回 ${item.user.nickname} 的${getTypeTag(item.type).props.children}？`,
      onOk: () => {
        message.success('已驳回');
      },
    });
  };

  const handleSubmitReview = async (values: any) => {
    try {
      setLoading(true);
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      message.success(`审核${values.result === 'approved' ? '通过' : '驳回'}`);
      setReviewModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error('操作失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="page-container">
      <div className="page-header">
        <Title level={4} className="page-title">资料审核</Title>
        <Text className="page-description">
          审核用户提交的资料信息，确保平台内容质量
        </Text>
      </div>

      <Card>
        <Table
          columns={columns}
          dataSource={mockReviewData}
          rowKey="id"
          loading={loading}
          pagination={{
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
          }}
        />
      </Card>

      {/* 审核详情弹窗 */}
      <Modal
        title="详细审核"
        open={reviewModalVisible}
        onCancel={() => setReviewModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedItem && (
          <div>
            <Row gutter={[24, 24]}>
              <Col span={24}>
                <Space>
                  <Avatar
                    src={selectedItem.user.avatar}
                    icon={<UserOutlined />}
                    size={64}
                  />
                  <div>
                    <Title level={5}>{selectedItem.user.nickname}</Title>
                    <Text type="secondary">
                      {selectedItem.user.age}岁 • {selectedItem.user.gender === 'male' ? '男' : '女'}
                    </Text>
                    <br />
                    <Text type="secondary">
                      提交时间：{formatDate(selectedItem.submitTime)}
                    </Text>
                  </div>
                </Space>
              </Col>

              <Col span={24}>
                <Divider />
                <Title level={5}>审核内容</Title>
                
                {selectedItem.type === 'profile' && selectedItem.content && (
                  <div>
                    <Text>个人简介：</Text>
                    <p style={{ 
                      background: '#f5f5f5', 
                      padding: '12px', 
                      borderRadius: '6px',
                      margin: '8px 0'
                    }}>
                      {selectedItem.content}
                    </p>
                  </div>
                )}

                {selectedItem.type === 'photo' && selectedItem.photos && (
                  <div>
                    <Text>上传照片：</Text>
                    <div style={{ 
                      display: 'flex', 
                      flexWrap: 'wrap', 
                      gap: '12px',
                      marginTop: '8px'
                    }}>
                      {selectedItem.photos.map((photo, index) => (
                        <Image
                          key={index}
                          width={120}
                          height={160}
                          src={photo}
                          style={{ borderRadius: '6px' }}
                        />
                      ))}
                    </div>
                  </div>
                )}
              </Col>

              <Col span={24}>
                <Divider />
                <Form
                  form={form}
                  layout="vertical"
                  onFinish={handleSubmitReview}
                >
                  <Form.Item
                    label="审核结果"
                    name="result"
                    rules={[{ required: true, message: '请选择审核结果' }]}
                  >
                    <Select placeholder="选择审核结果">
                      <Select.Option value="approved">通过</Select.Option>
                      <Select.Option value="rejected">驳回</Select.Option>
                    </Select>
                  </Form.Item>

                  <Form.Item
                    label="备注说明"
                    name="notes"
                    rules={[
                      { 
                        required: true, 
                        message: '请填写备注说明' 
                      }
                    ]}
                  >
                    <TextArea
                      rows={4}
                      placeholder="请填写审核备注，驳回时必须说明原因"
                    />
                  </Form.Item>

                  <Form.Item>
                    <Space>
                      <Button type="primary" htmlType="submit" loading={loading}>
                        提交审核
                      </Button>
                      <Button onClick={() => setReviewModalVisible(false)}>
                        取消
                      </Button>
                    </Space>
                  </Form.Item>
                </Form>
              </Col>
            </Row>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default UserReview;